package com.innovation.ic.sc.web.schedule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.innovation.ic.b1b.framework.util.HttpUtils;
import com.innovation.ic.sc.base.model.sc.User;
import com.innovation.ic.sc.base.pojo.constant.Constants;
import com.innovation.ic.sc.base.pojo.constant.ErpScoringReturnDataConstant;
import com.innovation.ic.sc.base.pojo.variable.ServiceResult;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.util.List;

/**
 * @desc   定时更新主账号评分
 * @author linuo
 * @time   2022年9月26日10:30:50
 */
@Component
public class PrimaryAccountScoreJobSchedule extends AbstractSchedule {
    private static final Logger log = LoggerFactory.getLogger(PrimaryAccountScoreJobSchedule.class);

    @XxlJob("primaryAccountScoreJob")
    private void primaryAccountScoreJob() {
        try {
            // 查询主账号列表
            ServiceResult<List<User>> allPrimaryAccountData = userService.getAllPrimaryAccountData();
            if(allPrimaryAccountData != null && allPrimaryAccountData.getResult().size() > 0){
                List<User> userList = allPrimaryAccountData.getResult();
                for(User user : userList){
                    Thread.sleep(200);
                    String id = user.getId();

                    // 查询erp的统计数据
                    String param = Constants.USER_ID + "=" + id;
                    String erpReturnData;
                    try {
                        erpReturnData = HttpUtils.sendGet(erpInterfaceAddressConfig.getGetSupplierScoringStatistics(), param, null);
                        log.info("查询账号:[{}]在erp的统计信息返回数据为:[{}]", id, erpReturnData);
                    }catch (Exception e){
                        log.info("调用erp接口出现问题,接口地址:[{}],参数:[{}],原因:", erpInterfaceAddressConfig.getGetSupplierScoringStatistics(), param, e);
                        continue;
                    }
                    if(Strings.isNullOrEmpty(erpReturnData)){
                        continue;
                    }

                    JSONObject json = (JSONObject) JSON.parse(erpReturnData);
                    if(null != json && !json.isEmpty() && json.getInteger(Constants.STATUS_) == 200){
                        JSONArray jsonArray = json.getJSONArray(Constants.DATA_FIELD);
                        if(null != jsonArray && !jsonArray.isEmpty()){
                            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                            if(null != jsonObject && !jsonObject.isEmpty()){
                                // 报价任务总数
                                Long count = jsonObject.getLong(ErpScoringReturnDataConstant.INQUIRY_COUNT);

                                // 已报价任务总数
                                Long haveQuotedCount = jsonObject.getLong(ErpScoringReturnDataConstant.QUOTE_COUNT);

                                // 20% 时间内报价任务总数
                                Long twentyPercentHaveQuotedCount = jsonObject.getLong(ErpScoringReturnDataConstant.QUOTE_COUNT1);

                                // 20% - 100% 时间内报价任务总数
                                Long twentyToHundredPercentHaveQuotedCount = haveQuotedCount - twentyPercentHaveQuotedCount;

                                // 被采纳的任务数
                                Long adoptionCount = jsonObject.getLong(ErpScoringReturnDataConstant.ACCEPT_COUNT);

                                // todo 需要大赢家返回订单相关数据才可以进行处理

                                // 采购下单次数
                                Long placeAnOrderCount = 0L;

                                // 订单取消次数
                                Long cancleOrderCount = 0L;

                                // 根据报价回复的及时性进行评分
                                BigDecimal timelinessScore = calculateTimelinessScore(count, twentyToHundredPercentHaveQuotedCount, twentyPercentHaveQuotedCount);

                                // 根据报价的回复率进行评分
                                BigDecimal reversionRateScore = calculateReversionRateScore(count, haveQuotedCount);

                                // 根据报价的被采纳率进行评分
                                BigDecimal adoptionRateScore = calculateAdoptionRateScore(count, adoptionCount);

                                // 根据订单的取消率进行评分
                                BigDecimal cancleOrderRateScore = calculateCancleOrderRateScore(placeAnOrderCount, cancleOrderCount);

                                // 计算供应商的总评分,计算公式: 1 + 及时性评分 + 回复率评分 +被采纳率评分 + 取消率评分, 最低1分,最高5分
                                BigDecimal countScore = BigDecimal.ONE.add(timelinessScore).add(reversionRateScore).add(adoptionRateScore).add(cancleOrderRateScore);
                                countScore = countScore.setScale(1, BigDecimal.ROUND_HALF_UP);
                                log.info("userId:[{}],总分:[{}]", id, countScore);
                                userService.updateScore(id, countScore);
                            }
                        }
                    }
                }
            }else{
                log.info("查询主账号列表为空,定时更新主账号评分结束");
            }
        } catch (Exception e) {
            log.error("定时更新供应商评分任务执行出现问题,原因:", e);
        }
    }

    /**
     * 根据订单的取消率进行评分
     * @param placeAnOrderCount 采购下单次数
     * @param cancleOrderCount 订单取消次数
     * @return 返回计算结果
     */
    private BigDecimal calculateCancleOrderRateScore(Long placeAnOrderCount, Long cancleOrderCount) {
        if(BigDecimal.valueOf(placeAnOrderCount).compareTo(BigDecimal.ZERO) == 0){
            return BigDecimal.ZERO;
        }
        BigDecimal divide = BigDecimal.valueOf(cancleOrderCount).divide(BigDecimal.valueOf(placeAnOrderCount), 1, BigDecimal.ROUND_HALF_UP);
        BigDecimal subtract = BigDecimal.ONE.subtract(divide);
        BigDecimal multiply = subtract.multiply(BigDecimal.valueOf(5));
        BigDecimal multiply1 = multiply.multiply(BigDecimal.valueOf(0.32));
        return multiply1;
    }

    /**
     * 计算报价的被采纳率评分
     * @param count 报价任务总数
     * @param adoptionCount 被采纳的任务数
     * @return 返回计算结果
     */
    private BigDecimal calculateAdoptionRateScore(Long count, Long adoptionCount) {
        if(BigDecimal.valueOf(count).compareTo(BigDecimal.ZERO) == 0){
            return BigDecimal.ZERO;
        }
        BigDecimal divide = BigDecimal.valueOf(adoptionCount).divide(BigDecimal.valueOf(count), 1, BigDecimal.ROUND_HALF_UP);
        BigDecimal multiply = divide.multiply(BigDecimal.valueOf(5));
        BigDecimal multiply1 = multiply.multiply(BigDecimal.valueOf(0.16));
        return multiply1;
    }

    /**
     * 计算报价的回复率评分
     * @param count 报价任务总数
     * @param haveQuotedCount 已报价任务总数
     * @return 返回计算结果
     */
    private BigDecimal calculateReversionRateScore(Long count, Long haveQuotedCount) {
        if(BigDecimal.valueOf(count).compareTo(BigDecimal.ZERO) == 0){
            return BigDecimal.ZERO;
        }
        BigDecimal multiply = BigDecimal.valueOf(haveQuotedCount).multiply(BigDecimal.valueOf(5));
        BigDecimal divide = multiply.divide(BigDecimal.valueOf(count), 1, BigDecimal.ROUND_HALF_UP);
        BigDecimal multiply1 = divide.multiply(BigDecimal.valueOf(0.16));
        return multiply1;
    }

    /**
     * 计算报价回复的及时性评分
     * @param count 报价任务总数
     * @param twentyToHundredPercentHaveQuotedCount 20% - 100% 时间内报价任务总数
     * @param twentyPercentHaveQuotedCount 20% 时间内报价任务总数
     * @return 返回计算结果
     */
    private BigDecimal calculateTimelinessScore(Long count, Long twentyToHundredPercentHaveQuotedCount, Long twentyPercentHaveQuotedCount) {
        long totalScore = twentyToHundredPercentHaveQuotedCount * 2 + twentyPercentHaveQuotedCount * 5;
        BigDecimal divide = BigDecimal.valueOf(totalScore).divide(BigDecimal.valueOf(count), 1, BigDecimal.ROUND_UP);
        BigDecimal multiply = divide.multiply(BigDecimal.valueOf(0.16));
        return multiply;
    }
}